import {defineStore} from "pinia"
import router from "@/router"

type tagType={name:string,title:string,fullPath:string,active:boolean,affix?:boolean,[key:string]:any}

const initTags=[
  {name:'home',title:'首页',fullPath:'/home',affix:true,active:false}, 
] 

export default defineStore('cachePages',{
    state:()=>({
      tags:JSON.parse(JSON.stringify(initTags)) as tagType[],
      maxLength:100,
    }),
    actions:{
      addTag(tag:tagType){
        // console.log(tag)
       if(this.tags.length==this.maxLength)
       {
         this.tags.forEach(v=>v.active=false)
         return 
       }
        //console.log(tag)
         this.tags.forEach(v=>v.active=false)
         this.tags.push({...tag,active:true})
      },
      deleteTag(index:number){
       //console.log(router.currentRoute)
        if(this.tags[index].affix) return
         const delTag=this.tags.splice(index,1)[0]
         // fullPath会带上跳转时传递query和params参数。
         if(delTag.fullPath==router.currentRoute.value.fullPath)
         {
          const nextTag=this.tags[index]
          if(nextTag) router.replace(this.tags[index].fullPath)
          else router.replace(this.tags[index-1].fullPath)
         }
      },
      activeTag({index,fullPath}:{index:number,fullPath:string}){
       // console.log('active',index)
         this.tags.forEach(v=>v.active=false)
         this.tags[index].active=true
         this.tags[index].fullPath=fullPath
      },
      setSort(sortNameArr:string[]){
         const nameToTagMap:objType={}
         this.tags.forEach(v=>{nameToTagMap[v.name]=v})
         const newTags:tagType[]=[]
         sortNameArr.forEach(v=>{
          const item=nameToTagMap[v]
          if(item) newTags.push(item)
         })
         this.tags=newTags
      },
      clearActive(){
        this.tags.forEach(v=>v.active=false)
      },
      clearRightTags(index:number){
        this.tags=this.tags.filter((v,i)=>i<=index || v.affix)
      },
      clearLeftTags(index:number){
        this.tags=this.tags.filter((v,i)=>i>=index || v.affix)
      },
      clearOtherTags(index:number){
        this.tags=this.tags.filter((v,i)=>i!=index || v.affix)
      },
      clearTags(isLogout=false){
        //console.log(isLogout)
          this.tags=this.tags.filter(v=>v.affix)
          if(!isLogout)
          router.replace(this.tags[0].fullPath)
      },
    },
    getters:{
      // 如果我们为页面组件提供了name属性，且name属性与路由配置的name属性相同，则可以用该属性作为keepAlive标签include的属性值
      nameList():string[]{
         return this.tags.map(v=>v.name)
      },
    }

})